<?php
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
    exit('Access Denied');
}
// 获取表模型
$table_configs = C::t('#erling_gridad_image#configs_image');

// 处理表单提交
if(submitcheck('configsubmit')) {
    $configs = $_POST['config'];
    foreach($configs as $key => $value) {
        $result = $table_configs->update_by_key($key, array('value' => $value));
        if($result['success'] === false) {
            $errors[] = "配置项 {$key} 更新失败：{$result['message']}";
        }
    }
    if(empty($errors)) {
        cpmsg('设置更新成功', 'action=plugins&operation=config&do='.$pluginid.'&identifier=erling_gridad_image&pmod=admin_config','succeed');
    } else {
        cpmsg(implode('<br>', $errors), 'action=plugins&operation=config&do='.$pluginid.'&identifier=erling_gridad_image&pmod=admin_config','error');
    }
}



// 获取所有配置
$configs = $table_configs->fetch_all();

// 处理积分类型数据
$extcredits_array = DB::fetch_all("SELECT * FROM %t WHERE skey LIKE %s", array('common_setting', 'extcredits%'));
if ($extcredits_array && isset($extcredits_array[0]['svalue'])) {
    $extcredits_data = unserialize($extcredits_array[0]['svalue']);
} else {
    $extcredits_data = [];
}

echo '<form method="post" action="'.ADMINSCRIPT.'?action=plugins&operation=config&do='.$pluginid.'&identifier=erling_gridad_image&pmod=admin_config">';
echo '<input type="hidden" name="formhash" value="'.FORMHASH.'" />';
echo '<table class="tb tb2">';
echo '<tr><th>配置名称</th><th>配置值</th><th>配置说明</th></tr>';

foreach($configs as $config) {
    echo '<tr>';
    echo '<td>'.$config['name'].'</td>';
    echo '<td>';
    if(in_array($config['key'], ['use_nofollow', 'enable_audit', 'bgcolor_on'])) {
        echo '<select name="config['.$config['key'].']">';
        echo '<option value="1" '.($config['value'] == 1 ? 'selected' : '').'>开启</option>';
        echo '<option value="0" '.($config['value'] == 0 ? 'selected' : '').'>关闭</option>';
        echo '</select>';
    } elseif(in_array($config['key'], ['daily_credit', 'monthly_credit', 'title_length', 'cache_time'])) {
        echo '<input type="number" min="1" name="config['.$config['key'].']" 
              value="'.dhtmlspecialchars($config['value']).'" style="width: 120px" />';
    } elseif(in_array($config['key'], ['default_color', 'default_bgcolor'])) {
        // 添加颜色选择器
        echo '<input type="text" name="config['.$config['key'].']" value="'.dhtmlspecialchars($config['value']).'" 
              style="width: 100px" oninput="this.nextElementSibling.value=this.value" />';
        echo '<input type="color" style="vertical-align:middle;margin-left:5px;padding:revert;width:27px;" 
              value="'.dhtmlspecialchars($config['value']).'" 
              onchange="this.previousElementSibling.value=this.value" />';
    } elseif($config['key'] == 'allowed_groups') {
        // 添加用户组选择
        $allowed_groups = dunserialize($config['value']);
        echo '<select name="config['.$config['key'].'][]" multiple="multiple" style="height:200px;width:200px;">';
        echo '<option value="clear" onclick="this.parentNode.querySelectorAll(\'option\').forEach(opt => opt.selected = false); this.selected = true">-- 清空选择 --</option>';
        
        // 会员用户组
        echo '<optgroup label="会员用户组">';
        foreach(C::t('common_usergroup')->fetch_all_by_type('member') as $group) {
            echo '<option value="'.$group['groupid'].'" '.(is_array($allowed_groups) && in_array($group['groupid'], $allowed_groups) ? 'selected' : '').'>'.$group['grouptitle'].'</option>';
        }
        echo '</optgroup>';
        
        // 自定义用户组
        echo '<optgroup label="自定义用户组">';
        foreach(C::t('common_usergroup')->fetch_all_by_type('special') as $group) {
            echo '<option value="'.$group['groupid'].'" '.(is_array($allowed_groups) && in_array($group['groupid'], $allowed_groups) ? 'selected' : '').'>'.$group['grouptitle'].'</option>';
        }
        echo '</optgroup>';
        
        echo '</select>';
        echo '<script>document.currentScript.parentNode.querySelector(\'select\').addEventListener(\'change\', function(e) {
            if(e.target.querySelector(\'option[value="clear"]:checked\')) {
                e.target.querySelectorAll(\'option\').forEach(opt => opt.selected = false);
            }
        });</script>';
    } elseif(in_array($config['key'], ['form_tip', 'contact_info'])) {
        echo '<textarea name="config['.$config['key'].']" style="width: 200px; height: 50px;">'.dhtmlspecialchars($config['value']).'</textarea>';
    } elseif($config['key'] == 'credit_type') {
        echo '<select name="config['.$config['key'].']">';
        foreach($extcredits_data as $i => $credit) {
            if($credit['available'] && !empty($credit['title'])) {
                echo '<option value="'.$i.'" '.($config['value'] == $i ? 'selected' : '').'>'.$credit['title'].' (extcredits'.$i.')</option>';
            }
        }
        echo '</select>';
    } else {
        echo '<input type="text" name="config['.$config['key'].']" value="'.dhtmlspecialchars($config['value']).'" />';
    }
    echo '</td>';
    echo '<td>'.$config['desc'].'</td>';
    echo '</tr>';
}

echo '</table>';
echo '<input type="submit" class="btn" name="configsubmit" value="提交保存" />';
echo '</form>';